import pygame
from main import *
import sys

import traceback

from pygame.locals import *

import tkinter as tk

import tkinter.messagebox

import pickle

class Menu_Button_Func():
    def __init__(self):
        self.game=Game_Main()
        self.screen=self.game.screen

        # pygame.mixer.init()
        # self.menu_sound = pygame.mixer.Sound("music/mune.wav")  # 选择菜单时的音效
        # self.menu_sound.set_volume(0.2)
        self.window = tk.Tk()

        self.window.title('欢迎来到飞机大战')
        self.window.geometry('450x300')
        self.window.geometry('+960+540')

        # 创建一个300X500的画布
        canvas = tk.Canvas(self.window , height=300 , width=500)
        # logo的路径
        self.image_file = tk.PhotoImage(file='image/pikaqiu.gif')
        numIdx = 18  # gif的帧数
        # 填充6帧内容到frames
        frames = [tk.PhotoImage(file='image/pikaqiu.gif' , format='gif -index %i' % (i)) for i in range(numIdx)]

        def update(idx) :  # 定时器函数
            frame = frames[idx]
            idx += 1  # 下一帧的序号：在0,1,2,3,4,5之间循环(共6帧)
            image = canvas.create_image(0 , 0 , anchor='nw' , image=frame)# 显示当前帧的图片# 什么位置插入logo图片
            canvas.pack(side='top')
            self.window.after(1000 , update , idx % numIdx)  # 0.1秒(100毫秒)之后继续执行定时器函数(update)
        self.window.after(0,update,0)  # 立即启动定时器函数(update) after方法就是个定时器
        tk.Label(self.window , text='用户名:').place(x=100 , y=150)
        tk.Label(self.window , text='密码:').place(x=100 , y=190)
        # 用户名输入框
        self.var_usr_name = tk.StringVar()
        entry_usr_name = tk.Entry(self.window , textvariable=self.var_usr_name)
        entry_usr_name.place(x=160 , y=150)
        # 密码输入框
        self.var_usr_pwd = tk.StringVar()
        entry_usr_pwd = tk.Entry(self.window , textvariable=self.var_usr_pwd , show='*')
        entry_usr_pwd.place(x=160 , y=190)


######注册函数
    def usr_sign_up(self):
        # 确认注册时的相应函数
        def signtowcg():
            # 获取输入框内的内容
            nn = new_name.get()
            np = new_pwd.get()
            npf = new_pwd_confirm.get()

            # 本地加载已有用户信息,如果没有则已有用户信息为空
            try:
                with open('usr_info.pickle', 'rb') as usr_file:
                    exist_usr_info = pickle.load(usr_file)
            except FileNotFoundError:
                exist_usr_info = {}

                # 检查用户名存在、密码为空、密码前后不一致
            if nn in exist_usr_info:
                tk.messagebox.showerror('错误', '用户名已存在')
            elif np == '' or nn == '':
                tk.messagebox.showerror('错误', '用户名或密码为空')
            elif np != npf:
                tk.messagebox.showerror('错误', '密码前后不一致')
            # 注册信息没有问题则将用户名密码写入数据库
            else:
                exist_usr_info[nn] = np
                with open('usr_info.pickle', 'wb') as usr_file:
                    pickle.dump(exist_usr_info, usr_file)
                tk.messagebox.showinfo('欢迎', '注册成功')
                # 注册成功关闭注册框
                window_sign_up.destroy()
        # 新建注册界面
        window_sign_up = tk.Toplevel(self.window)
        window_sign_up.geometry('350x200')
        window_sign_up.title('注册')
        # 用户名变量及标签、输入框
        new_name = tk.StringVar()
        tk.Label(window_sign_up, text='用户名：').place(x=10, y=10)
        tk.Entry(window_sign_up, textvariable=new_name).place(x=150, y=10)
        # 密码变量及标签、输入框
        new_pwd = tk.StringVar()
        tk.Label(window_sign_up, text='请输入密码：').place(x=10, y=50)
        tk.Entry(window_sign_up, textvariable=new_pwd, show='*').place(x=150, y=50)
        # 重复密码变量及标签、输入框
        new_pwd_confirm = tk.StringVar()
        tk.Label(window_sign_up, text='请再次输入密码：').place(x=10, y=90)
        tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*').place(x=150, y=90)
        # 确认注册按钮及位置
        bt_confirm_sign_up = tk.Button(window_sign_up, text='确认注册',
                                       command=signtowcg)
        bt_confirm_sign_up.place(x=150, y=130)



    # 登录函数
    def usr_log_in(self):
        # 输入框获取用户名密码
        usr_name = self.var_usr_name.get()
        usr_pwd = self.var_usr_pwd.get()
        # 从本地字典获取用户信息，如果没有则新建本地数据库
        try:
            with open('usr_info.pickle', 'rb') as usr_file:
                usrs_info = pickle.load(usr_file)
        except FileNotFoundError:
            with open('usr_info.pickle', 'wb') as usr_file:
                usrs_info = {'admin': 'admin'}
                pickle.dump(usrs_info, usr_file)
        # 判断用户名和密码是否匹配
        if usr_name in usrs_info:
            if usr_pwd == usrs_info[usr_name] :
                tk.messagebox.showinfo(title='welcome',
                                       message='欢迎您：' + usr_name)
                with open("record_login_user_name.txt", "w") as f:
                    f.write(str(usr_name))
                self.window.destroy()
                try:
                    self.Menu()
                    pass
                except SystemExit:
                    pass


            else:
                tk.messagebox.showerror(message='密码错误')
        # 用户名密码不能为空
        elif usr_name == '' or usr_pwd == '':
            tk.messagebox.showerror(message='用户名或密码为空')
        # 不在数据库中弹出是否注册的框
        else:
            is_signup = tk.messagebox.askyesno('欢迎', '您还没有注册，是否现在注册')
            if is_signup:
                self.usr_sign_up()
                ##########################################################################################################
                # 菜单界面
    def create_button(self):
        # 登录 注册按钮
        bt_login = tk.Button(self.window , text='登录' , command=self.usr_log_in)
        bt_login.place(x=140 , y=230)
        bt_logup = tk.Button(self.window , text='注册' , command=self.usr_sign_up)
        bt_logup.place(x=210 , y=230)
        bt_logquit = tk.Button(self.window , text='退出' , command=self.usr_sign_quit)
        bt_logquit.place(x=280 , y=230)
    def usr_sign_quit(self):
        self.window.destroy()
    # "关于"界面
    def About(self) :
        # 娱乐图片
        about_fun_img = pygame.image.load("image/about_fun.JPG")
        about_fun_rect = about_fun_img.get_rect()
        # 娱乐图片
        about_fun2_img = pygame.image.load("image/about_fun2.png")
        about_fun2_rect = about_fun2_img.get_rect()

        # 返回按钮
        comeback1_img = pygame.image.load("image/comeback1.png").convert_alpha()  # 返回按钮
        comeback2_img = pygame.image.load("image/comeback2.png").convert_alpha()
        comeback_img = comeback1_img  # 设置默认图片
        comeback_rect = comeback1_img.get_rect()
        comeback_rect.left , comeback_rect.top = 1920-100 , 1080 - 100

        about_font = pygame.font.Font("font/myfont.ttf" , 35)
        Author_text = about_font.render("Author: 王鹏超" , True , (255,255,255))
        Email_text = about_font.render("E-mail: 17603453135@163.com" , True ,(255,255,255))
        Language_text = about_font.render("Language: Python" , True , (255,255,255))
        Bgm_text = about_font.render("Bgm: 《Friendship》" , True , (255,255,255))

        while True :
            for event in pygame.event.get() :
                if event.type == QUIT :
                    pygame.quit()
                    sys.exit()

                elif event.type == MOUSEMOTION :
                    # 返回按钮
                    if comeback_rect.collidepoint(event.pos) :
                        comeback_img = comeback1_img
                    else :
                        comeback_img = comeback2_img

                elif event.type == MOUSEBUTTONDOWN :
                    # collidepoint(event.pos),自动检测鼠标是否停留在pos内，如果是则返回True
                    if event.button == 1 and comeback_rect.collidepoint(event.pos) :
                        #self.menu_sound.play()
                        self.Menu()

            self.screen.blit(about_fun2_img , about_fun2_rect)
            self.screen.blit(comeback_img , comeback_rect)
            self.screen.blit(Author_text , (10 , 90))
            self.screen.blit(Email_text , (10 , 140))
            self.screen.blit(Language_text , (10 , 190))
            self.screen.blit(Bgm_text , (10 , 240))
            self.screen.blit(about_fun_img , (0 , 700 - about_fun_rect.height))

            pygame.display.flip()



    # 帮助界面
    def Help(self) :
        # 背景图片
        help_fun_img = pygame.image.load("image/help_fun.jpg")
        help_fun_rect = help_fun_img.get_rect()
        # 返回按钮
        comeback1_img = pygame.image.load("image/comeback1.png").convert_alpha()  # 返回按钮
        comeback2_img = pygame.image.load("image/comeback2.png").convert_alpha()
        comeback_img = comeback1_img  # 设置默认图片
        comeback_rect = comeback1_img.get_rect()
        comeback_rect.left , comeback_rect.top = 1000 - 100 , 700 - 100

        while True :
            for event in pygame.event.get() :
                if event.type == QUIT :
                    pygame.quit()
                    sys.exit()

                elif event.type == MOUSEMOTION :
                    # 返回按钮
                    if comeback_rect.collidepoint(event.pos) :
                        comeback_img = comeback1_img
                    else :
                        comeback_img = comeback2_img

                elif event.type == MOUSEBUTTONDOWN :
                    # collidepoint(event.pos),自动检测鼠标是否停留在pos内，如果是则返回True
                    if event.button == 1 and comeback_rect.collidepoint(event.pos) :
                        self.menu_sound.play()
                        self.Menu()


            self.screen.blit(help_fun_img , (0 , 0))
            self.screen.blit(comeback_img , comeback_rect)
            pygame.display.flip()

    def Menu(self):

        # 娱乐图片1
        menu_fan_img = pygame.image.load("image/menu_fun.png").convert_alpha()  # 娱乐图片
        menu_fan_rect = menu_fan_img.get_rect()
        menu_fan_rect.left, menu_fan_rect.top = 0, 0
        # 娱乐图片2
        menu_fan2_img = pygame.image.load("image/menu_fun2.png").convert_alpha()  # 娱乐图片
        menu_fan2_rect = menu_fan2_img.get_rect()
        menu_fan2_rect.left, menu_fan2_rect.top = 1920 - menu_fan2_rect.width, 0

        # 开始游戏按钮
        begin_game1_img = pygame.image.load("image/begin_game1.png").convert_alpha()  # 开始游戏按钮
        begin_game2_img = pygame.image.load("image/begin_game2.png").convert_alpha()
        begin_game_img = begin_game1_img
        begin_game_rect = begin_game1_img.get_rect()
        begin_game_rect.left, begin_game_rect.top = 264 + 350, 486 - 200

        # 帮助按钮
        help1_img = pygame.image.load("image/help1.png").convert_alpha()  # 帮助按钮
        help2_img = pygame.image.load("image/help2.png").convert_alpha()
        help_img = help1_img
        help_rect = help1_img.get_rect()
        help_rect.left, help_rect.top = 264 + 350, 424 + 0

        # 关于按钮
        about1_img = pygame.image.load("image/about1.png").convert_alpha()  # 关于按钮
        about2_img = pygame.image.load("image/about2.png").convert_alpha()
        about_img = about1_img
        about_rect = about1_img.get_rect()
        about_rect.left, about_rect.top = 264 + 350, 424 + 150

        # 鼠标解除按钮音效
        is_sound = True

        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                # 检测鼠标是否移动到暂停游戏按钮
                elif event.type == MOUSEMOTION:
                    # 开始游戏按钮
                    if begin_game_rect.collidepoint(event.pos):
                        begin_game_img = begin_game2_img
                    else:
                        begin_game_img = begin_game1_img
                    # 帮助按钮
                    if help_rect.collidepoint(event.pos):
                        help_img = help1_img
                    else:
                        help_img = help2_img
                    # 关于按钮
                    if about_rect.collidepoint(event.pos):
                        about_img = about1_img
                    else:
                        about_img = about2_img

                elif event.type == MOUSEBUTTONDOWN:
                    # collidepoint(event.pos),自动检测鼠标是否停留在pos内，如果是则返回True
                    if event.button == 1 and about_rect.collidepoint(event.pos):
                        # self.menu_sound.play()
                        self.About()
                    elif event.button == 1 and begin_game_rect.collidepoint(event.pos):
                        # self.menu_sound.play()
                        self.game.start_game()
                    elif event.button == 1 and help_rect.collidepoint(event.pos):
                        # self.menu_sound.play()
                        self.Help()


            self.screen.blit(menu_fan2_img , menu_fan2_rect)
            self.screen.blit(menu_fan_img , (0 , 0))
            self.screen.blit(begin_game_img , begin_game_rect)
            self.screen.blit(help_img , help_rect)
            self.screen.blit(about_img , about_rect)

            pygame.display.flip()




    def mainloop(self):
        self.window.mainloop()


if __name__ == '__main__' :
    b=Menu_Button_Func()
    b.create_button()
    b.mainloop()

